<template>
<div class="goodsInventory">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search">查询</el-button>
    </template>
    <el-form inline :model="model" label-width="100px" @submit.native.prevent>
      <el-form-item label="商品名称:">
        <el-input v-model="model.name" clearable></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    border
    :getDataWay="{
      data: tableData
    }"
    :columns="columns">
    <el-table-column slot="stock" label="库存" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <el-input-number v-if="row.edit" style="width:100%" step-strictly :controls="false" v-model="row.stock" :min="0" size="mini"></el-input-number>
        <span v-else>{{row.stock}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="150">
      <template v-slot="{row}">
        <div class="table-buttons">
          <template v-if="row.edit">
            <el-button type="primary" size="mini" @click="saveSku(row)">保存</el-button>
            <el-button size="mini" @click="row.edit = false;editing = null">取消</el-button>
          </template>
          <el-button v-else type="primary" size="mini" @click="editSku(row)">编辑</el-button>
        </div>
      </template>
    </el-table-column>
  </y-table>
</div>
</template>

<script>
export default {
  name: "goodsInventory",
  data(){
    return{
      model:{
        name: ''
      },
      editing: null,
      tableData: [],
      columns: [{
        label: "商品名称",
        prop: "productName",
        minWidth: 200
      },{
        label: "规格",
        prop: "spData",
        minWidth: 100
      },{
        label: "库存",
        prop: "stock",
        template: true
      }]
    }
  },
  created(){
    this.search();
  },
  methods:{
    search(){
      this.editing = null;
      this.$yAxios({
        url: this.$api.goods.skuInventoryPage,
        data: this.model,
        loading: true,
      }, info => {
        this.tableData = info.map(item => {
          this.$set(item, 'edit', false);
          return item;
        });
        this.editing = null;
      });
    },
    editSku(row){
      if(!this.editing){
        this.editing = row;
        this.$set(row, 'edit', true);
      }else{
        this.$alert('存在其他正在编辑未保存的数据，请先保存其他数据再编辑本条数据', {
          confirmButtonText: '确定'
        });
      }
    },
    saveSku(row){
      this.$yAxios({
        url: this.$api.goods.updateSku,
        data: row,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.editing = null;
        this.search();
      })
    },
  }
}
</script>

<style scoped>

</style>
